<template>
  <EcDialog v-model="dialogVisible" :hidden-horizontal="false" body-height="400px" class="form-dialog" width="60%">
    <!-- 标题 -->
    <template #title>
      <div class="dialog-title">
        <SvgIcon icon="setting" size="18" style="margin-right: 5px;"></SvgIcon>
        <span>{{ dialogTitle }}</span>
      </div>
    </template>

    <!-- 内容 -->
    <div v-loading="loading" class="body-wrapper" element-loading-text="加载中...">
      <el-table :data="tableItemList.slice((pageData.pageNum - 1) * pageData.pageSize, pageData.pageNum * pageData.pageSize)" fit highlight-current-row>
        <el-table-column key="image_url" align="center" label="图片" prop="image_url" width="66">
          <template #default="scope">
            <UploadImage v-if="scope.row.id >= 0" v-model="scope.row.image_url" :disabled="true" :file-size="10" :show-tip="false" height="42px" width="42px"/>
          </template>
        </el-table-column>

        <el-table-column key="spec_key_name" align="left" label="规格" min-width="280" prop="spec_key_name" show-overflow-tooltip>
        </el-table-column>

        <el-table-column key="store_count" align="center" label="当前库存" prop="store_count" min-width="120">
          <template #default="scope">
            <span>{{ scope.row.id > 0 ? scope.row.store_count : '' }}</span>
          </template>
        </el-table-column>

        <el-table-column key="update_type" align="center" label="类型" prop="update_type" min-width="100">
          <template #default="scope">
            <el-select v-model="scope.row.update_type" placeholder="" style="width: 76px">
              <el-option :value="1" label="入库"/>
              <el-option :value="0" label="出库"/>
            </el-select>
          </template>
        </el-table-column>

        <el-table-column key="update_count" align="left" header-align="center" label="数量" min-width="210" prop="update_count" show-overflow-tooltip>
          <template #default="scope">
            <el-input-number v-model="scope.row.update_count" :min="0" :precision="0" :step="1" controls-position="right" style="width: 7.2rem"/>
            <span v-if="scope.row.id > 0" style="margin-left: 8px">= {{ calculateNewCount(scope.row) }}</span>
            <el-button v-if="scope.row.id < 0" link style="margin-left: 12px" type="primary" @click="handleItemFill(scope.row)">批量设置</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页操作 -->
      <el-pagination v-if="tableItemList.length > 10"
                     :current-page="pageData.pageNum"
                     :page-size="pageData.pageSize"
                     :page-sizes="[5, 10, 30, 50]"
                     :total="tableItemList.length"
                     background
                     class="table-pagination"
                     layout="total, sizes, prev, pager, next"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"/>
    </div>
    <!-- 底部操作区域 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button :loading="dataLoading" @click="dialogVisible = false">取 消</el-button>
        <el-button v-permission="['shop:goods:update']" :loading="dataLoading" type="primary" @click="onSubmitForm()">确 定</el-button>
      </span>
    </template>
  </EcDialog>
</template>

<script lang="ts" setup>
import { computed, reactive, ref } from 'vue';
import { EcDialog } from '@/components/dialog';
import { SvgIcon } from '@/components/icon';
import useDialog from '@/hooks/use-dialog.ts';
import { goodsBatchStoreCount, GoodsSpec, goodsSpecList } from '@/api/api-shop.ts';
import { UploadImage } from '@/components/upload';
import { ElLoading, ElMessageBox, ElNotification } from 'element-plus';

defineOptions({name: 'goods-store-form'})

const loading = ref(false); // 表单是否加载中
const {dialogVisible, dialogTitle} = useDialog(false);

/** 判断数据是否处于加载中 */
const dataLoading = computed(() => {
  return loading.value;
})

/** 商品规格信息 */
const itemList = ref<GoodsSpec[]>([]);
const goodsId = ref(0);

/** 打开弹窗 */
const open = async (id: number) => {
  dialogTitle.value = '商品库存管理';
  dialogVisible.value = true;
  itemList.value = [];
  pageData.pageNum = 1;
  pageData.pageSize = 5;
  goodsId.value = id;
  // 加载数据
  if (id) {
    loading.value = true
    try {
      const {data} = await goodsSpecList(id)
      itemList.value = data;
      itemList.value.forEach(it => {
        it.update_type = 1;
        it.update_count = 0;
      });
    } finally {
      loading.value = false
    }
  }
}
// 提供 open 方法，用于打开弹窗
defineExpose({open});

/** 表单提交 */
const emit = defineEmits(['refresh']);
const onSubmitForm = async () => {
  // 弹窗确认提示
  ElMessageBox.confirm('是否确认进行此操作？', {
    title: '提示',
    type: 'warning',
    showCancelButton: true,
    confirmButtonText: '确认',
    cancelButtonText: '取消',
  }).then((action) => {
    let updates = [];
    // @ts-ignore
    itemList.value.forEach(it => updates.push({id: it.id, type: it.update_type, count: it.update_count}))
    let params = {
      id: goodsId.value,
      store_updates: updates
    }
    const loading = ElLoading.service({
      lock: true,
      text: '正在提交中...',
      background: 'rgba(0, 0, 0, 0.2)'
    })
    goodsBatchStoreCount(params).then(response => {
      // 提示信息
      ElNotification({title: '成功', message: '操作完成', type: 'success', duration: 2000})
      // 发送操作成功的事件
      emit('refresh')
      // 隐藏窗口
      dialogVisible.value = false
    }).finally(() => loading.close())
  });
};

const calculateNewCount = (row: any): number => {
  // 1:入库 2:出库
  let newCount = 0;
  if (row.update_type == 1) {
    newCount = row.store_count + row.update_count;
  } else {
    newCount = row.store_count - row.update_count;
  }
  return Math.max(0, newCount)
};

/** 列表数据 */
const tableItemList = computed(() => {
  let specList = itemList.value || [];
  if (specList.length > 5) {
    let temp: GoodsSpec[] = [{
      id: -1,
      goods_id: 0,
      spec_key: 'temp',
      spec_key_ids: [],
      price: undefined,
      price_cost: undefined,
      price_integral: undefined,
      store_count: 0,
      update_type: 1,
      update_count: 0,
    }]
    return temp.concat(specList)
  }
  return specList
});

/** 批量填充 */
const handleItemFill = (item: GoodsSpec) => {
  if (!item || item.id >= 0) return;

  // 循环填充
  itemList.value.forEach(it => {
    it.update_type = item.update_type;
    it.update_count = item.update_count;
  })
};

const pageData = reactive({
  pageNum: 1,
  pageSize: 5,
});

const handleSizeChange = (val) => {
  pageData.pageSize = val;
};

const handleCurrentChange = (val) => {
  pageData.pageNum = val;
};
</script>

<style lang="scss" scoped>
.form-dialog {
  .el-select,
  .el-input-number {
    max-width: 13rem;
  }
}

.body-wrapper {
  .table-pagination {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    margin-top: 12px;
  }
}
</style>
